<template>
  <div class="image-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>{{$route.query.id ? '修改文章' : '发布文章'}}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form ref="form" :model="article" label-width="80px">
        <el-form-item label="标题 :" style="width:400px;">
          <el-input v-model="article.title"></el-input>
        </el-form-item>
        <el-form-item label="内容 :">
          <el-tiptap
            v-model="article.content"
            :extensions="extensions"
            height = "400"
            placeholder="请输入文章内容"
          >
          </el-tiptap>
        </el-form-item>
        <el-form-item label="封面 :">
          <el-radio-group v-model="article.cover.type">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
          <template v-if="article.cover.type > 0">
            <div class="wrapImage-box">
              <imageVue
                v-for="(image ,index) in article.cover.type" :key="index"
                @receiveImage="onReceiveImage(index, $event)"
                :sendImage="article.cover.images[index]"
              ></imageVue>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="频道 :">
          <el-select v-model="article.channel_id" placeholder="请选择">
            <el-option v-for="(channel, index) in channelsData" :key="index" :label="channel.name" :value="channel.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onAddArticle(false)">{{$route.query.id ? '确认' : '发布'}}</el-button>
          <el-button @click="onAddArticle(true)">存为草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
// 引入文章相关api接口
import { channels, addArticle, editArticleData, updateArticle } from '@/api/article'
// 导入图片上传相关api接口
import { uploadImage } from '@/api/image'
// 局部引入富文本编辑器
import {
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Link,
  Image,
  Iframe,
  CodeBlock,
  Blockquote,
  Italic,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  TodoItem,
  TodoList,
  TextAlign,
  Indent,
  LineHeight,
  HorizontalRule,
  HardBreak,
  TrailingNode,
  History,
  Table,
  TableHeader,
  TableCell,
  TableRow,
  FormatClear,
  TextColor,
  TextHighlight,
  Preview,
  Print,
  Fullscreen,
  SelectAll,
  FontType
} from 'element-tiptap'
// import element-tiptap 样式
import 'element-tiptap/lib/index.css'
// 导入自定义组件
import imageVue from '@/views/publish/components/image'
export default {
  name: 'appPublish',
  data () {
    return {
      article: {
        title: '', // 文章标题
        content: '', // 文章内容
        cover: { // 文章封面
          type: 0,
          images: []
        },
        channel_id: '' // 文章频道id
      },
      channelsData: [], // 文章频道列表
      // 编辑器的 extensions
      // 它们将会按照你声明的顺序被添加到菜单栏和气泡菜单中
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 5 }),
        new Bold({ bubble: true }), // 在气泡菜单中渲染菜单按钮
        new Underline(),
        new Italic(),
        new Strike(),
        new Link(),
        new Image({
          // 默认会把图片生成 base64 字符串和内容存储在一起，如果需要自定义图片上传
          uploadRequest (file) {
            // 如果接口要求 Content-Type 是 multipart/form-data，则请求体必须使用 FormData
            const fd = new FormData()
            fd.append('image', file)
            // 第1个 return 是返回 Promise 对象
            // 为什么？因为 axios 本身就是返回 Promise 对象
            return uploadImage(fd).then(res => {
              // 这个 return 是返回最后的结果
              return res.data.data.url
            })
          } // 图片的上传方法，返回一个 Promise<url>
        }),
        new ListItem(),
        new BulletList(),
        new OrderedList(),
        new TodoItem(),
        new TodoList(),
        new Iframe(),
        new CodeBlock(),
        new Blockquote(),
        new TextAlign(),
        new Indent(),
        new LineHeight(),
        new HorizontalRule(),
        new HardBreak(),
        new TrailingNode(),
        new History(),
        new Table(),
        new TableHeader(),
        new TableCell(),
        new TableRow(),
        new FormatClear(),
        new TextColor(),
        new TextHighlight(),
        new Preview(),
        new Print(),
        new Fullscreen(),
        new SelectAll(),
        new FontType()
      ]
    }
  },
  methods: {
    // 获取文章频道
    async channelsLists () {
      const res = await channels()
      try {
        this.channelsData = res.data.data.channels
      } catch (err) {
        return Promise.reject(err)
      }
    },
    // 发表文章
    async onAddArticle (draft) {
      // 判断$route.query.id是否存在,来决定使用添加文章,或者是修改文章,请求接口
      const articleId = this.$route.query.id
      if (articleId) {
        // 修改文章
        // updateArticle(articleId, data, draft = false)articleId为文章id,data为提交的post请求体,draft为提交的状态(false发表状态 || true草稿状态)
        const res = await updateArticle(articleId, this.article, draft)
        try {
          if (res.status === 201) {
            this.$message({
              message: `${draft ? '已存入' : '修改成功'}`,
              type: 'success'
            })
          } else {
            this.$message({
              message: `${draft ? '为存入' : '修改失败'}`,
              type: 'error'
            })
          }
          // 跳转文章列表页
          this.$router.push({
            name: 'article'
          })
        } catch (err) {
          return Promise.reject(err)
        }
      } else {
        // 增加文章
        // addArticle(data,draft) data为提交的post请求体,draft为提交的状态(false发表状态 || true草稿状态)
        const res = await addArticle(this.article, draft)
        try {
          if (res.status === 201) {
            this.$message({
              message: `${draft ? '已存入' : '发布成功'}`,
              type: 'success'
            })
          } else {
            this.$message({
              message: `${draft ? '未存入' : '发布失败'}`,
              type: 'error'
            })
          }
          // 跳转到文章列表页
          this.$router.push({
            name: 'article'
          })
        } catch (err) {
          return Promise.reject(err)
        }
      }
    },
    // 获取编辑文章-指定文章数据
    async loadEditArticle () {
      // editArticleData(articleId)文章id
      const res = await editArticleData(this.$route.query.id)
      try {
        // 编辑文章,显示相对应文章的值
        this.article = res.data.data
      } catch (err) {
        return Promise.reject(err)
      }
    },
    // 获取子组件数据
    onReceiveImage (index, childData) {
      // 获取子组件数据保存在文章封面数组中
      this.article.cover.images[index] = childData
    }
  },
  components: {
    'el-tiptap': ElementTiptap, // a富文本编辑器
    imageVue
  },
  created () {
    // 执行获取文章频道列表方法
    this.channelsLists()
    // 如果route.query.id存在,就执行获取指定文章列表数据方法
    if (this.$route.query.id) {
      this.loadEditArticle()
    }
  }
}
</script>
<style lang="less">
.image-container{
  .box-card{
    .el-form{
      .el-form-item{
        .wrapImage-box{
          display: flex;
          .upImage-container{
            &:nth-child(2){
              margin: 0 20px;
            }
            .el-image{
              .image-slot{
                display: flex;
                justify-content: center;
                align-items: center;
                width: 100%;
                height: 100%;
                background: #f5f7fa;
                color: #909399;
                font-size: 14px;
                i{
                  font-size: 30px;
                }
              }
            }
          }
        }
      }
    }
  }
}
.el-dialog__wrapper{
  .el-tabs{
    .el-tab-pane{
      display: flex;
      justify-content: center;
      .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
      }
      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
    }
  }
}
</style>
